package com.jiuwan.gamepass.auth;

import com.jiuwan.gamepass.dto.authDto.Result;
import com.jiuwan.gamepass.dto.authDto.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * 功能目的描述 ：用于登录失败的处理；类         ========>>>>>>>>>>>
 * @author： pang-yun
 * @date： 2021-06-23 14:43
 */
@Component
public class MyAuthenticationFailureHandler extends JSONAuthentication implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result result=null;
        if (exception instanceof AccountExpiredException){
            //账号过期
            result =Result.error(ResultCode.USER_ACCOUNT_EXPIRED);
        }else if (exception instanceof BadCredentialsException){
            //密码错误
            result=Result.error(ResultCode.USER_CREDENTIALS_ERROR);
        }else if (exception instanceof CredentialsExpiredException){
            //密码过期
            result=Result.error(ResultCode.USER_CREDENTIALS_EXPIRED);
        }else if (exception instanceof DisabledException){
            //账号不可用
            result=Result.error(ResultCode.USER_ACCOUNT_DISABLE);
        }else if (exception instanceof LockedException){
            //账户锁定
            result=Result.error(ResultCode.USER_ACCOUNT_LOCKED);
        }else if (exception instanceof InternalAuthenticationServiceException){
            //用户不存在
            result=Result.error(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }else {
            //其他错误
            result=Result.error(ResultCode.COMMON_FAIL);
        }

       /* //处理编码方式
        response.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        // 这是SpringBoot中jackson提供给我们的能将类或者其他对象转换为json的一种方式
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));*/

        this.WriteJSON(request,response,result);

    }
}
